﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using Wedn.Core.Common;
using Wedn.Core.Service;
using Wedn.Core.Utility;

namespace Wedn.Core.Entity
{
    /// <summary>
    /// 文章实体拓展模型类
    /// </summary>
    [Serializable]
    public class Post : IComparable<Post>
    {
        public int CompareTo(Post other)
        {
            if (other.pubDate != this.pubDate)
            {
                return this.PubDate.CompareTo(other.pubDate);
            }
            if (other.Update != this.Update)
            {
                return this.Update.CompareTo(other.Update);
            }
            return this.Id.CompareTo(other.Id);
        }
        #region 非字段

        /// <summary>
        /// 是否为新文章
        /// </summary>
        public bool IsNew
        {
            get { return DateTime.Now.Subtract(this.pubDate).Days < 2; }
        }

        private string url;
        /// <summary>
        /// 内容链接地址URL
        /// </summary>
        /// <remarks>
        /// desc:自动判断是否支持URL重写
        /// </remarks>
        public string Url
        {
            get
            {
                if (string.IsNullOrEmpty(url))
                {
                    string siteurl = Config.SiteUrl.TrimEnd('/');
                    //if (Utils.IsSupportUrlRewriter)
                    //{
                    //如果系统支持UrlRewriter
                    string permalink = Setting.Permalink;
                    
                    if (!string.IsNullOrEmpty(permalink))
                    {
                        url = Regex.Replace(permalink, "{siteurl}", siteurl);
                        url = Regex.Replace(url, "{dir}", "post");
                        url = Regex.Replace(url, "{alias}", this.Slug);
                        url = Regex.Replace(url, "{slug}", this.Slug);
                        url = Regex.Replace(url, "{id}", this.Id.ToString());
                    }
                    else
                    {
                        url = string.Format("{0}/?type=post&post={1}", siteurl, this.Id);
                    }
                    //}
                    //else
                    //{
                    //    url = string.Format("{0}/?postid={1}", siteurl, this.Id);
                    //}s
                }
                return url;
            }
        }

        /// <summary>
        /// 文章缩略图
        /// </summary>
        public string Img
        {
            get
            {
                string src;
                Match match = Regex.Match(this.Content, "<img.+?src=\"(.+?)\".+?>");
                if (match.Length > 0)
                {
                    src = match.Groups[1].Value;
                }
                else
                {
                    src = "../resource/images/random/tb" + StringHelper.GetRandom(1, 20) + ".jpg";
                }
                return src;
            }
        }

        /// <summary>
        /// 分页URL
        /// </summary>
        public string PageUrl
        {
            get
            {
                return "";
            }
        }

        /// <summary>
        /// a标签链接html
        /// </summary>
        public string Link
        {
            get { return string.Format("<a href=\"{0}\">{1}</a>", this.Url, this.Title); }
        }

        /// <summary>
        /// 订阅URL
        /// </summary>
        public string FeedUrl
        {
            get
            {
                return string.Format("{0}feed/comment/postid/{1}{2}", Config.SiteUrl, this.Id, Setting.RewriteExtension);
            }
        }

        /// <summary>
        /// 订阅连接
        /// </summary>
        public string FeedLink
        {
            get
            {
                return string.Format("<a href=\"{0}\" title=\"订阅:{1} 的评论\">订阅</a>", this.FeedUrl, this.Title);
            }
        }

        /// <summary>
        /// 文章 摘要
        /// 根据设置而定,可为摘要,正文,不显示
        /// </summary>
        public string Detail
        {
            get
            {
                switch (Setting.PostShowType)
                {
                    //case "summary":
                    //    return StringHelper.CutString(StringHelper.RemoveHtml(this.Content), 160, "...");
                    case "full":
                        return this.Content;
                    case "none":
                        return string.Empty;
                    default:
                        return StringHelper.CutString(StringHelper.RemoveHtml(this.Content), 160, "...");
                }
            }
        }

        /// <summary>
        /// Rss 详情
        /// 根据设置而定,可为摘要,正文,前200字,空等
        /// </summary>
        public string FeedDetail
        {
            get
            {
                switch (Setting.PostShowType)
                {
                    //case "summary":
                    //    return StringHelper.CutString(StringHelper.RemoveHtml(this.Content), 160, "...");
                    case "full":
                        return this.Content;
                    case "none":
                        return string.Empty;
                    default:
                        return StringHelper.CutString(StringHelper.RemoveHtml(this.Content), 160, "...");
                }
            }
        }

        private User auther;
        /// <summary>
        /// 作者
        /// </summary>
        public User Author
        {
            get
            {
                if (auther == null)
                {
                    UserManager userManager = new UserManager();
                    auther = userManager.GetUser(this.AutherId);
                }
                return auther;
            }
        }

        private List<Comment> comments;
        /// <summary>
        /// 文章评论对象集合
        /// </summary>
        public List<Comment> Comments
        {
            get
            {
                if (comments == null)
                {
                    CommentManager commentManager = new CommentManager();
                    comments = commentManager.GetCommentList(Common.CommentStatus.Approved, this.id, -1, 0);
                }
                return comments == null ? new List<Comment>() : comments;
            }
        }

        private List<Term> terms = null;
        private List<Term> categorys = new List<Term>();
        /// <summary>
        /// 所属分类集合
        /// </summary>
        public List<Term> Categorys
        {
            get
            {
                if (terms == null)
                {
                    TermManager termManager = new TermManager();
                    terms = termManager.GetTermList(this.id, ObjectType.Post);
                    terms = terms == null ? new List<Term>() : terms;
                }
                if (categorys.Count == 0)
                {
                    foreach (Term item in terms)
                    {
                        if (item.Type == 1)
                        {
                            categorys.Add(item);
                        }
                    }
                }
                return categorys;
            }
        }
        private string categoryLink;
        /// <summary>
        /// 所属分类 记录文章超链形式类别信息
        /// </summary>
        public string CategoryLink
        {
            get
            {
                if (categoryLink == null)
                {
                    StringBuilder sbd = new StringBuilder();
                    foreach (Term item in Categorys)
                    {
                        string html = string.Format("<a href=\"{0}\" title=\"查看 {0} 下的文章\">{1}</a>", "s", item.Name);
                        sbd.Append(html);
                        sbd.Append("，");
                    }
                    if (sbd.Length > 1)
                        sbd.Remove(sbd.Length - 1, 1);
                    categoryLink = sbd.ToString();
                }
                return categoryLink;
            }
        }

        private string categoryName;
        /// <summary>
        /// 所属分类名称列表, 以逗号分割
        /// </summary>
        public string CategoryName
        {
            get
            {
                if (categoryName == null)
                {
                    StringBuilder sbd = new StringBuilder();
                    foreach (Term item in Categorys)
                    {
                        sbd.Append(item.Name);
                        sbd.Append("，");
                    }
                    if (sbd.Length > 1)
                        sbd.Remove(sbd.Length - 1, 1);
                    categoryName = sbd.ToString();
                }
                return categoryName;
            }
        }

        private List<Term> tags = new List<Term>();
        /// <summary>
        /// 对应标签集合
        /// </summary>
        public List<Term> Tags
        {
            get
            {
                if (terms == null)
                {
                    TermManager termManager = new TermManager();
                    terms = termManager.GetTermList(this.id, ObjectType.Post);
                    terms = terms == null ? new List<Term>() : terms;
                }
                if (tags.Count == 0)
                {
                    foreach (Term item in terms)
                    {
                        if (item.Type == 0)
                        {
                            tags.Add(item);
                        }
                    }
                }
                return tags;
            }
        }

        private string tagLink;
        /// <summary>
        /// 对应标签 记录文章超链形式标签信息
        /// </summary>
        public string TagLink
        {
            get
            {
                if (tagLink == null)
                {
                    StringBuilder sbd = new StringBuilder();
                    foreach (Term item in Tags)
                    {
                        string html = string.Format("<a href=\"{0}\">{1}</a>", "../" + item.Slug, item.Name);
                        sbd.Append(html);
                        sbd.Append("，");
                    }
                    if (sbd.Length > 1)
                        sbd.Remove(sbd.Length - 1, 1);
                    tagLink = sbd.ToString();
                }
                return tagLink;
            }
        }

        //private Post[] preAndNext;
        ///// <summary>
        ///// 下一篇文章(新)
        ///// </summary>
        //public Post Next
        //{
        //    get
        //    {
        //        if (preAndNext == null)
        //        {
        //            PostManager postManager = new PostManager();
        //            preAndNext = postManager.GetPreviousAndNext(this);
        //        }
        //        return preAndNext[1];
        //    }
        //}

        ///// <summary>
        ///// 上一篇文章(旧)
        ///// </summary>
        //public Post Previous
        //{
        //    get
        //    {
        //        if (preAndNext == null)
        //        {
        //            PostManager postManager = new PostManager();
        //            preAndNext = postManager.GetPreviousAndNext(this);
        //        }
        //        return preAndNext[0];
        //    }
        //}


        #endregion

        #region 所有字段
        private int id;
        private string slug;
        private string title;
        private string subTitle;
        private DateTime pubDate = DateTime.Now;
        private DateTime update = DateTime.Now;
        private string content;
        private string excerpt;
        private string template;
        private int autherId;
        private int viewCount = 0;
        private int commentCount = 0;
        private int commentStatus = 0;
        private int status = 0;
        private int type = 0;
        private bool isTop = false;
        private int pingStatus = 0;
        private string pinged;
        private string password;
        private int parentId = 0;
        #endregion

        #region 对外公共属性
        /// <summary>
        /// 主键(自增长)字段
        /// </summary>
        public int Id
        {
            get { return id; }
            set { id = value; }
        }
        /// <summary>
        /// 文章别名(伪静态用)字段
        /// </summary>
        public string Slug
        {
            get { return slug; }
            set { slug = value; }
        }
        /// <summary>
        /// 文章标题字段
        /// </summary>
        public string Title
        {
            get { return title; }
            set { title = value; }
        }
        /// <summary>
        /// 文章副标题字段
        /// </summary>
        public string SubTitle
        {
            get { return subTitle; }
            set { subTitle = value; }
        }
        /// <summary>
        /// 文章发布日期字段
        /// </summary>
        public DateTime PubDate
        {
            get { return pubDate; }
            set { pubDate = value; }
        }
        /// <summary>
        /// 文章最后编辑时间字段
        /// </summary>
        public DateTime Update
        {
            get { return update; }
            set { update = value; }
        }
        /// <summary>
        /// 文章正文字段
        /// </summary>
        public string Content
        {
            get { return content; }
            set { content = value; }
        }
        /// <summary>
        /// 文章摘要字段
        /// </summary>
        public string Excerpt
        {
            get { return excerpt; }
            set { excerpt = value; }
        }
        /// <summary>
        /// 文章模版字段
        /// </summary>
        public string Template
        {
            get { return template; }
            set { template = value; }
        }
        /// <summary>
        /// 文章作者ID字段
        /// </summary>
        public int AutherId
        {
            get { return autherId; }
            set { autherId = value; }
        }
        /// <summary>
        /// 文章浏览次数字段
        /// </summary>
        public int ViewCount
        {
            get { return viewCount; }
            set { viewCount = value; }
        }
        /// <summary>
        /// 文章评论次数字段
        /// </summary>
        public int CommentCount
        {
            get { return commentCount; }
            set { commentCount = value; }
        }
        /// <summary>
        /// 文章评论状态(0:所有人可评论, 1:用户可评论, 2:不允许评论...)
        /// </summary>
        public int CommentStatus
        {
            get { return commentStatus; }
            set { commentStatus = value; }
        }
        /// <summary>
        /// 文章状态字段(0:公开, 1:加密, 2:私密, 3:继承, 4:草稿, 5:自动草稿, 6:回收站...)
        /// </summary>
        public int Status
        {
            get { return status; }
            set { status = value; }
        }
        /// <summary>
        /// 文章类型(0:Post, 1:Page, 2:Media...)
        /// </summary>
        public int Type
        {
            get { return type; }
            set { type = value; }
        }
        /// <summary>
        /// 文章是否置顶字段
        /// </summary>
        public bool IsTop
        {
            get { return isTop; }
            set { isTop = value; }
        }
        /// <summary>
        /// 文章Ping状态(0:Open,1:JustUser, 2,Close...)
        /// </summary>
        public int PingStatus
        {
            get { return pingStatus; }
            set { pingStatus = value; }
        }
        /// <summary>
        /// 文章Ping状态(占时无用)
        /// </summary>
        public string Pinged
        {
            get { return pinged; }
            set { pinged = value; }
        }
        /// <summary>
        /// 文章密码字段
        /// </summary>
        public string Password
        {
            get { return password; }
            set { password = value; }
        }
        /// <summary>
        /// 文章父ID字段
        /// </summary>
        public int ParentId
        {
            get { return parentId; }
            set { parentId = value; }
        }
        #endregion

        #region 构造函数
        public Post() { }
        ///// <summary>
        ///// 文章实体模型类构造函数
        ///// </summary>
        ///// <param name="id">文章编号</param>
        ///// <param name="slug">文章别名</param>
        ///// <param name="titile">文章标题</param>
        ///// <param name="subTitle">文章副标题</param>
        ///// <param name="pubDate">文章发布日期</param>
        ///// <param name="update">文章最后编辑时间</param>
        ///// <param name="content">文章正文</param>
        ///// <param name="commenCount">文章评论次数</param>
        ///// <param name="viewCount">文章浏览次数</param>
        ///// <param name="autherId">文章作者ID</param>
        ///// <param name="status">文章状态(0:发布, 1:加密, 2:私密, 4:草稿, 5:回收站)</param>
        ///// <param name="type">文章类型</param>
        ///// <param name="password">文章密码</param>
        //public Post(int id, string slug, string titile, string subTitle, DateTime pubDate, DateTime update, string content, int commenCount, int viewCount, int autherId, int status, string type, string password, int parentId)
        //{
        //    this.id = id;
        //    this.slug = slug;
        //    this.title = titile;
        //    this.subTitle = subTitle;
        //    this.pubDate = pubDate;
        //    this.update = update;
        //    this.content = content;
        //    this.commentCount = commenCount;
        //    this.viewCount = viewCount;
        //    this.autherId = autherId;
        //    this.status = status;
        //    this.type = type;
        //    this.password = password;
        //}
        #endregion
    }
}
